'''
@author: Vafrous
@contributor: Morroc

*Note*: this file is intended to be placed in the Shaiya-Updater folder.
It WILL run into errors otherwise.

This script will download all necessary patches into a newly created
'Patches' folder within your Shaiya-Updater directory.
'''

import os
import time
import urllib
from sys import argv
from subprocess import Popen

def download (url):
    print url
    process = Popen(["./wget/wget", "-cNxnH", url])
    process.communicate()
    process.wait()
    
# changes to directory of the downloader.py file
abspath = os.path.abspath(argv[0])
dname = os.path.dirname(abspath)
os.chdir(dname)

# downloads the UpdateVersion.ini file and checks the PatchFileVersion
download('http://shaiya-us.patch.aeriagames.com/Shaiya/UpdateVersion.ini')

uv = open('./Shaiya/UpdateVersion.ini', 'r')
for line in uv:
    if line[:17] == 'PatchFileVersion=':
        patchFileVersion = int(line[17:len(line)])

# opens the Version.ini file and checks the CurrentVersion
v = open('Version.ini', 'r')
for line in v:
    if line[:15] == 'CurrentVersion=':
        currentVersion = int(line[15:len(line)])

if currentVersion == patchFileVersion :
    print "#################### Your game is already updated! Exiting! ####################"
    time.sleep(5)
    exit()
else:
    print "#################### Downloading Patches ####################"

# empty array for the patch URLs
urllist = []

# fills array with necessary patch URLs
for i in range(currentVersion + 1, patchFileVersion + 1):
    
    url = 'http://shaiya-us.patch.aeriagames.com/Shaiya/patch/ps'

    if i < 10:
        url = url + '000'
    elif i < 100:
        url = url + '00'
    elif i < 1000:
        url = url + '0'
    url = url + str(i) + '.patch'

    urllist.append(url)

# calculates total size of the download & prints in MB   
print "#################### Calculating Total Size Download ####################"
downloadSize = 0
for i in urllist:
    site = urllib.urlopen(i)
    downloadSize += int(site.info()['Content-Length'])

downloadSize = float(downloadSize)
downloadSize = downloadSize / (1024*1024)
print "########################################################################"
print "####################"
print '#################### Total size of Download: %.2fMB ####################' % downloadSize
print "####################"
print "########################################################################"
# downloads each patch
for i in urllist:
    download(i)
    print 'Done!\n'
    
print "#################### All Patches Finished Downloading! ####################"
time.sleep(5)
print "#################### Starting Server! ####################"
time.sleep(2)
process = Popen(["hfs"])
